這邊我做的第一件事是在 Fragment 裡面引用 Binding,大家可以參考我的 code,或是參考資料的第一個連結。
class HomeFragment : Fragment() {
private var binding: FragmentHomeBinding? = null //在這裡宣告 binding
private val viewBinding get() = binding!!
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater,container,false) // 設定參數
val view = viewBinding.root
viewBinding.textView2.text = "Hello" // 修改初始外觀
return view // 輸出畫面
}
override fun onDestroyView() {
super.onDestroyView()
binding = null // 避免內存洩漏
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
HomeFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
再來我們需要新增按鈕觸發的事件,填入下面的 code 大家可以試試點擊每個按鈕讓 TextView 顯示不同的字
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentHomeBinding.inflate(inflater,container,false)
val view = viewBinding.root
viewBinding.firstButton.setOnClickListener{
viewBinding.textView2.text = "1"
}
viewBinding.secondButton.setOnClickListener{
viewBinding.textView2.text = "2"
}
viewBinding.thirdButton.setOnClickListener{
viewBinding.textView2.text = "3"
}
viewBinding.fouthButton.setOnClickListener{
viewBinding.textView2.text = "4"
}
return view
}
抱歉了各位,我沒有想到資料的架構要怎麼處理,可能需要一天的時間思考一下,所以今天要很尷尬地斷在這裡了
Android-View Binding
https://cheenjame.medium.com/android-view-binding-36aca5f9c2f2